package common

import (
	"github.com/dgrijalva/jwt-go"
	"time"
)

//自定义claims，可以加入自定义的字段，
//在解析token时可以获取这些自定义字段为业务功能去服务
type MyCustomClaims struct {
	Username           string `json:"username"` //用户名
	Uid                int    `json:"id"`       //主键id
	jwt.StandardClaims        //jwt包的标准claims
}

func GetToken(username string, uid int) string {
	//创建claims，
	claims := MyCustomClaims{
		username,
		uid,
		jwt.StandardClaims{ //设定过期时间和起始时间和生成者
			ExpiresAt: time.Now().Add(time.Hour * 1).Unix(),
			IssuedAt:  time.Now().Unix(),
			Issuer:    "homin",
		},
	}

	//生成token
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	//获取完整的签名令牌,传入签名的字节
	//tokenstr, err := token.SigningString()
	mySigningKey := []byte("hominniubi")
	tokenstr, err := token.SignedString(mySigningKey)
	if err != nil {
		//todo 获取token失败
	}
	return tokenstr
}

func ParseToken(tokenstr string) (*jwt.Token, MyCustomClaims, error) {

	claims := MyCustomClaims{}

	//调用jwt的ParseWithClaims
	token, err := jwt.ParseWithClaims(tokenstr, &claims, func(token *jwt.Token) (interface{}, error) {
		return []byte("hominniubi"), nil
	})

	return token, claims, err
}
